package net.ib.mtalk.service;

import net.ib.mntalk.protocol.Common;
import net.ib.mntalk.protocol.Common.NotificationInfo;
import net.ib.mntalk.protocol.Common.UUIDMsg;
import net.ib.mntalk.protocol.Common.UUIDSliceRange;
import net.ib.mntalk.protocol.Session.GetMessagesReq;
import net.ib.mtalk.database.helper.InboxDatabaseHelper;
import net.ib.mtalk.global.GlobalPreferences;
import net.ib.mtalk.network.NetResultReceiver;
import net.ib.mtalk.network.NetResultReceiver.Receiver;
import net.ib.mtalk.network.serverapi.Ping;
import net.ib.mtalk.network.task.GetMessagesTask;
import net.ib.mtalk.service.ReadmarkReceivedHandler.ReadmarkCallback;
import net.ib.mtalk.ui.chat.ChatController;
import net.ib.mtalk.ui.chat.ChatListActivity;
import net.ib.mtalk.ui.inbox.InboxListActivity;
import net.ib.mtalk.util.MTalkLogWriter;
import android.content.Context;
import android.os.Handler;
import android.util.Log;

public class MessageReceivedHandler extends SelectResultHandler {

	// 종료를 위한 수행 카운터
	private int mFinishCount;
	
	private Handler mHandler;
	private Context mContext;
	private NotificationInfo mNotiInfo;
	
	private UUIDMsg messageChangeNotiUuid;
	
	private ChatController mChatController;
	
	/**
	 * 한 개의 NotificationInfo에 대하여 객체가 한 개씩 생성된다.
	 * @param notificationInfo {@link Common#MESSAGE_RECEIVED}에 해당하는 객체
	 */
	MessageReceivedHandler(Context context, NotificationInfo notificationInfo) {
		super(context, notificationInfo);
		mNotiInfo = notificationInfo;
		mContext = context;
		mFinishCount = 0;
	}

	@Override
	protected void onWork(Handler handler) {
		
		mHandler = handler;

		finish();
		// 메시지 요청을 하자!!
		UUIDSliceRange range = new UUIDSliceRange();
		// 시작점은 이전에 받았던 마지막 노티 타임 UUID
		// 끝점은 방금 통보받은 노티 타임 UUID
		// TODO : 내림 차순으로 변경
		range.setStart(GlobalPreferences.getLastMessageReceivedNotiUuid());
		range.setEnd(mNotiInfo.getNotiId().getNotiUuid());
		range.setAscending(false);	// 내림차순
		range.setMaxCount(ChatListActivity.GET_MESSAGE_COUNT);
		
		mNotiInfo.getNotiId().getMessageOption().getViewUuid();
		
		GetMessagesReq getMessagesReq = new GetMessagesReq();
		getMessagesReq.setViewUuid(mNotiInfo.getNotiId().getMessageOption().getViewUuid());
		getMessagesReq.setRange(range);
		
		// 새로운 메시지만 받는다 // ChatListActivity.GET_MESSAGE_COUNT
		try{
			GetMessagesTask task = new GetMessagesTask(mContext, mHandler, mNotiInfo.getNotiId().getMessageOption().getViewUuid(), getMessagesReq);
			task.execute();
		}catch(Exception e){
			MTalkLogWriter.e(e);
		}
	}

	/**
	 * 작업을 마치는 예제.
	 */
	private void finishMyJob() {
		if(mFinishCount <= 1){
			MTalkLogWriter.d("MessageReceivedHandler : FINISH()");
			finish();	// 넌 죽었음. // TODO : 자원 낭비 하지말고 살아 있어라~
		}else{
			mFinishCount--;
		}
	}
	
	private NetResultReceiver mCallback = null;
	
	protected NetResultReceiver makeNewCallback() {
		mCallback = new NetResultReceiver(mHandler, new MessageReceivedCallback());	// 준비됐으니 새 리시버를 만들어준다.
		return mCallback;
	}
	
	class MessageReceivedCallback implements NetResultReceiver.Receiver {

		@Override
		public void onNetResult(int resultCode, Object sentObject,
				Object receivedObject) {
			finishMyJob();
		}

		@Override
		public void onNetError(int resultCode, Object sentObject) {
			finishMyJob();
		}
		
	}
}
